package com.cloudcc.boot.oaservice;

import com.cloudcc.boot.constants.UtilConstants;
import com.cloudcc.boot.core.CCObject;
import com.cloudcc.boot.core.CCService;
import com.cloudcc.boot.core.ServiceResult;
import com.cloudcc.boot.model.UserRequest;
import com.cloudcc.boot.web.OA_Operate;
import com.cloudcc.boot.web.OA_Token;
import com.google.common.collect.Lists;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import jakarta.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import static com.cloudcc.boot.core.CCService.userInfo;

@Controller
@RequestMapping(value = "/api")
@Slf4j
public class ContractClass {
    @Value("${system.localurl:''}")
    public String localurl;
    @Value("${system.url:''}")
    public String url;
    @Value("${system.oaurl:''}")
    public String oaurl;
    @Autowired
    public OA_Token oa;
    @Autowired
    private OA_Operate oa_operate;
    String contract_workflowId_fd= UtilConstants.Public.contract_workflowId_fd;//流程ID_风电
    String contract_xsnr_tableDBName_fd= UtilConstants.Public.contract_xsnr_tableDBName_fd;//合同_销售内容_子表表名_风电
    String contract_skjh_tableDBName_fd= UtilConstants.Public.contract_skjh_tableDBName_fd;//合合同_付款信息_子表表名_风电
    String contract_workflowId_gj= UtilConstants.Public.contract_workflowId_gj;//流程ID_国际
    String contract_xsnr_tableDBName_gj= UtilConstants.Public.contract_xsnr_tableDBName_gj;//合同_销售内容_子表表名_国际
    String contract_skjh_tableDBName_gj= UtilConstants.Public.contract_skjh_tableDBName_gj;//合同_付款信息_子表表名_国际

    /**
     * author : 黄涛 on 2024-07-08
     * 合同推送OA
     */
    @ResponseBody
    @RequestMapping(value = "/contract_push", produces = "text/html;charset=UTF-8")
    @ApiOperation(value = "")
    public String contract_push(UserRequest userRequest, HttpServletRequest request) throws Exception {
        String userRquestStr = JSONObject.fromObject(userRequest).toString();//入参
        log.info("contract_push请求参数{}", userRquestStr);
        JSONObject returnJson = new JSONObject();
        CCObject interfacerecordObj = new CCObject("interfacerecord");//接口同步记录
        CCService cs = new CCService(userInfo);

        try {
            String recordID = userRequest.getRecordID() == null ? "" : userRequest.getRecordID();//主表记录ID
            String objectApiName = "contract";//对象名
            String workflowId = "";//流程ID
            String xsnr_tablename = "";//销售内容子表数据库表名
            String fkxx_tablename = "";//付款信息子表数据库表名
            String isnextflow = "0";//isnextflow ：新建流程是否默认提交到第二节点，可选值为[0 ：不流转 1：流转 (默认)]
            String oa_user_type = "主账号";//账号类型：主账号、次账号
            String ywlx = oa_operate.getRecordValue(objectApiName, recordID,"ywlx");//业务类型
            //查询记录类型
            String recordtypeName = oa_operate.getType(objectApiName, recordID);
            if (recordtypeName.indexOf("风电公司")>=0){
                workflowId = contract_workflowId_fd;
                xsnr_tablename = contract_xsnr_tableDBName_fd;
                fkxx_tablename = contract_skjh_tableDBName_fd;
            }else if ("国际业务".equals(recordtypeName)&&"轨道交通".equals(ywlx)){
                workflowId = contract_workflowId_gj;
                xsnr_tablename = contract_xsnr_tableDBName_gj;
                fkxx_tablename = contract_skjh_tableDBName_gj;
                oa_user_type = "次账号";
            }else{
                returnJson.put("id", recordID);
                returnJson.put("code", "ERROR");
                returnJson.put("errMsg", "根据主表记录类型及业务类型，未匹配到对应流程ID");
                return returnJson.toString();
            }
            //查询oa经办人ID
            String oa_user_id = oa_operate.getOaUserId(objectApiName, recordID, oa_user_type);
            //查询oa经办人姓名
            String owneridccname = oa_operate.getCRMOwner(objectApiName,recordID);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date nowDate = new Date(); // 当前日期Date
            String currentTime = sdf.format(nowDate);
            //处理主表
            List<JSONObject> mainList = oa_operate.dealOAMainParam(objectApiName, recordID, "合同", oa_user_type);
            //处理子表
            List<JSONObject> subList = Lists.newArrayList();
            List<JSONObject> subOneList = oa_operate.dealOASubParam("xsnr", recordID, "htmc", "销售内容", oa_user_type);//子表：销售内容
            if (CollectionUtils.isNotEmpty(subOneList)) {
                JSONObject object = new JSONObject();
                object.put("tableDBName", xsnr_tablename);
                object.put("workflowRequestTableRecords", subOneList);
                subList.add(object);
            }
            List<JSONObject> subTwoList = oa_operate.dealOASubParam("cloudccskjh", recordID, "htbh", "付款信息", oa_user_type);//子表：付款信息（收款计划）
            if (CollectionUtils.isNotEmpty(subTwoList)) {
                JSONObject object = new JSONObject();
                object.put("tableDBName", fkxx_tablename);
                object.put("workflowRequestTableRecords", subTwoList);
                subList.add(object);
            }
            if (CollectionUtils.isEmpty(mainList)) {
                returnJson.put("code", "ERROR");
                returnJson.put("errMsg", "主表数据为空！");
                return returnJson.toString();
            }
            log.info("===================================");
            log.info("list==size{}==={}", mainList.size(), JSONArray.fromObject(mainList).toString());
            JSONObject param = new JSONObject();
            param.put("mainData", mainList);
            if (CollectionUtils.isNotEmpty(subList)) {
                param.put("detailData", subList);
            }
            JSONObject otherParams = new JSONObject();
            otherParams.put("isnextflow", isnextflow);
            param.put("otherParams", otherParams);
            param.put("workflowId", workflowId);
            param.put("requestName","合同-"+owneridccname+"-"+currentTime);
            //TODO 调接口传 param
            String oa_path = oaurl + "/api/workflow/paService/doCreateRequest";//OA创建流程接口
            log.info("osSendPost-->oa_path参数：{}", oa_path);
            log.info("osSendPost-->oa_user_id参数：{}", oa_user_id);
            log.info("osSendPost-->param参数：{}", param.toString());
            String data = oa.osSendPost(oa_path, oa_user_id, param.toString());
            log.info("========================");
            log.info("OA返回参数：：" + data);
            if (data.length() > 0) {
                returnJson = JSONObject.fromObject(data);
            } else {
                returnJson.put("code", "ERROR");
                returnJson.put("errMsg", "OA接口无返回");
            }
            interfacerecordObj.put("url", oa_path);//url
            interfacerecordObj.put("crcs", param.toString());//传入参数
            interfacerecordObj.put("zxzt", "处理成功");//执行状态
        } catch (Exception e) {
            returnJson.put("code", "ERROR");
            returnJson.put("errMsg", e + "");

            log.info("========================");
            log.info("报错信息：" + e.toString());

            interfacerecordObj.put("zxzt", "处理失败");//执行状态
        } finally {
            interfacerecordObj.put("fhcs", returnJson.toString());//返回参数
            //写入数据 newObj
            ServiceResult sr = cs.insert(interfacerecordObj);
        }
        return returnJson.toString();
    }

    /**
     * author : 黄涛 on 2024-07-08
     * 接收OA回写合同数据
     */
    @ResponseBody
    @RequestMapping(value = "/contract_receive", produces = "text/html;charset=UTF-8")
    @ApiOperation(value = "")
    public String contract_receive(@RequestBody UserRequest userRequest, HttpServletRequest request) throws Exception {
        String userRquestStr = JSONObject.fromObject(userRequest).toString();//入参
        log.info("contract_receive请求参数{}", userRquestStr);
        JSONObject returnJson = new JSONObject();
        CCService cs = new CCService(userInfo);
        CCObject interfacerecordObj = new CCObject("interfacerecord");//接口同步记录
        interfacerecordObj.put("url", localurl+"api/contract_receive");//url
        interfacerecordObj.put("crcs", userRquestStr);//传入参数

        try {
            String dataStr = userRequest.getData() == null ? "" : userRequest.getData().toString();//data数据
            String objectApiName = "contract";//对象名
            log.info("========================");
            log.info("data参数：：" + dataStr);
            if (dataStr.length() == 0) {
                returnJson.put("result", "false");
                returnJson.put("returnInfo", "data数据为空！");
                return returnJson.toString();
            }
            List<CCObject> main_List = JSONArray.fromObject(dataStr);
            JSONObject mainObj = new JSONObject();
            if (main_List != null && main_List.size() > 0) {
                mainObj = JSONObject.fromObject(main_List.get(0));
            }
            if (mainObj != null && mainObj.size() == 0) {
                returnJson.put("result", "false");
                returnJson.put("returnInfo", "主表数据为空！");
                return returnJson.toString();
            }

            //销售内容子表
            if (mainObj.containsKey("salsDetail")){
                String salsDetailStr = mainObj.getString("salsDetail");
                log.info("subOneList子表传入数据========="+salsDetailStr);
                if (salsDetailStr.length()>0){
                    JSONArray salsDetailArr = JSONArray.fromObject(salsDetailStr);
                    List<JSONObject> subOneList = oa_operate.dealCRMSubParam(salsDetailArr, "销售内容");//子表：销售内容
                    log.info("subOneList子表转换后数据=============="+subOneList.toString());
                    if (CollectionUtils.isNotEmpty(subOneList)) {
                        String subObjectApiName= "xsnr";
                        String oneArrayStr = subOneList.toString();
                        //接口推送
                        JSONObject parObj = new JSONObject();
                        parObj.put("serviceName", "upsert"); //服务名
                        parObj.put("objectApiName", subObjectApiName); //对象名
                        parObj.put("data", oneArrayStr); //查询条件
                        String relStr = cs.CCPost(cs.path, parObj.toString());
                        log.info("subOneList子表保存结果============"+relStr);
                    }
                }
            }
            //付款信息（收款计划）子表
            if (mainObj.containsKey("payDetail")){
                String payDetailStr = mainObj.getString("payDetail");
                log.info("subTwoList子表传入数据========="+payDetailStr);
                if (payDetailStr.length()>0){
                    JSONArray payDetailArr = JSONArray.fromObject(payDetailStr);
                    List<JSONObject> subTwoList = oa_operate.dealCRMSubParam(payDetailArr, "付款信息");//子表：付款信息（收款计划）
                    log.info("subTwoList子表转换后数据============="+subTwoList.toString());
                    if (CollectionUtils.isNotEmpty(subTwoList)) {
                        String subObjectApiName= "cloudccskjh";
                        String twoArrayStr = subTwoList.toString();
                        //接口推送
                        JSONObject parObj = new JSONObject();
                        parObj.put("serviceName", "upsert"); //服务名
                        parObj.put("objectApiName", subObjectApiName); //对象名
                        parObj.put("data", twoArrayStr); //查询条件
                        String relStr = cs.CCPost(cs.path, parObj.toString());
                        log.info("subTwoList子表保存结果============"+relStr);
                    }
                }
            }
            //合同主表
            List<JSONObject> mainList = oa_operate.dealCRMMainParam(objectApiName, mainObj, "合同");
            log.info("转换后主表数据==========" + mainList);
            //主表数据保存
            String putArrayStr = mainList.toString();
            //接口推送
            JSONObject parObj = new JSONObject();
            parObj.put("serviceName", "upsert"); //服务名
            parObj.put("objectApiName", objectApiName); //对象名
            parObj.put("data", putArrayStr); //查询条件
///            System.out.println("parObj = " + parObj);
            String relStr = cs.CCPost(cs.path, parObj.toString());

            returnJson = JSONObject.fromObject(relStr);
            log.info("保存主表数据返回结果：=======" + returnJson);
            interfacerecordObj.put("zxzt", "处理成功");//执行状态
        } catch (Exception e) {
            returnJson.put("result", "false");
            returnJson.put("returnInfo", e + "");
            returnJson.put("returnCode", "-1");

            log.info("========================");
            log.info("报错信息：" + e.toString());

            interfacerecordObj.put("zxzt", "处理失败");//执行状态
        } finally {
            interfacerecordObj.put("fhcs", returnJson.toString());//返回参数
            //写入数据 newObj
            ServiceResult sr = cs.insert(interfacerecordObj);
        }
        return returnJson.toString();
    }
}
